package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/global"
	"hft/tools"
)

type Price struct{}

func (*Price) CreatePrice(data *admin.Price, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("该账户信息不存在")
	}

	var city *admin.Region

	err = global.OC_DB.Where("manage_id = ?", account.ID).First(&city).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	data.City = int(city.ID)

	err = global.OC_DB.Create(&data).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*Price) EditPrice(data *admin.Price, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("该账户信息不存在")
	}

	var city *admin.Region

	err = global.OC_DB.Where("manage_id = ?", account.ID).First(&city).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	if data.City != int(city.ID) {
		return errors.New("你无权修改该城市信息")
	}

	err = global.OC_DB.Model(&admin.Price{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"id":         data.ID,
		"sort":       data.Sort,
		"price_type": data.PriceType,
		"max":        data.Max,
		"min":        data.Min,
	}).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*Price) GetPriceList(claims tools.BaseClaims) (list []*admin.Price, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("该账户信息不存在")
	}

	var city *admin.Region

	err = global.OC_DB.Where("manage_id = ?", account.ID).First(&city).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	var searchList []*admin.Price

	global.OC_DB.Order("sort desc").Where("city = ?", city.ID).Find(&searchList)

	return searchList, nil
}

func (*Price) Delete(ids []int) (err error) {

	var prices []*admin.Price

	global.OC_DB.Find(&prices, ids)

	global.OC_DB.Unscoped().Delete(&prices)

	return nil

}

var PriceService = new(Price)
